$(function () {
    var $table = $('#groupLists');
    action = "addGroup";
    var oTable = new TableInit($table,'/UserManage/getGroupList');
    oTable.Init();

    
    var oButtonInit = new ButtonInit($table,action);
    oButtonInit.Init();

    
    var icon = {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    };

    $("form[name='groupForm']").bootstrapValidator({
        feedbackIcons: icon,
        live: 'enabled', 
        //表单域配置
        fields: {
            groupName: {
                validators: {
                    notEmpty: {message: '请输入组名称'},
                    stringLength: { 
                        min: 2,
                        max: 30,
                        message: '用户名长度必须在2到30之间'
                    },
                    remote: { 
						url: '/UserManage/checkgroupname',  
						message: '组名称已存在', 
						type: 'POST',
						data : {
							groupName : function() {
								return $("#groupName").val();
							},
							groupId : function() {
								return $("#groupId").val();
							}
						}
                    }
                }
            },
            phoneNumber : {
                validators : {
                    notEmpty : {
                        message : "请输入电话号码"
                    },
                    regexp: {
                          regexp: /(^(\d{3,4}-)?\d{6,8}$)|(^(\d{3,4}-)?\d{6,8}(-\d{1,5})?$)|^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/,
                          message:'请输入正确的电话号码'
                    }
            	}  
        	}
    	}
    })
});


var TableInit = function ($table,url) {
    var oTableInit = new Object();
    
    oTableInit.Init = function () {
        $table.bootstrapTable({
            url: url,         
            method: 'get',                      
            striped: true,                      
            cache: false,                       
            pagination: true,                   
            sortable: false,                     
            sortOrder: "asc",                   
            queryParams: oTableInit.queryParams,
            sidePagination: "server",
            search: false,      
            pageNumber:1,                       
            pageSize: 10,                       
            pageList: [1,10, 25, 50, 100],                              
            strictSearch: true,
            showColumns: true,                  
            showRefresh: true,                  
            minimumCountColumns: 2,             
            clickToSelect: true,                
            height: 500,                        
            uniqueId: "id",                     
            showToggle:true,                    
            cardView: false,                    
            detailView: false,                
            columns: [{
                checkbox: true
            }, 
            {
                title: '序号',
                align: 'center',
                halign: 'center',
                formatter: function (value, row, index) {
                    var options = $table.bootstrapTable('getOptions');
                    return options.pageSize * (options.pageNumber - 1) + index + 1;
                }
            },
            {
                field: 'id',
                title: '用户id',
                visible:false
            }, {
                field: 'group_name',
                title: '组名称'
            }, {
                field: 'phone_number',
                title: '联系方式'
            }, {
                field: 'added_by',
                title: '添加人'
            }, 
            {
                field: 'added_datetime',
                title: '添加时间'
            }
            ]
        });
    };

    oTableInit.queryParams = function (params) {
        var temp = {   
            limit: params.limit,   
            offset: params.offset,  
            serGroupName: $("#serGroupName").val()
        };
        return temp;
    };
    return oTableInit;
};


var ButtonInit = function ($table) {
    var oInit = new Object();
    var postdata = {};

    oInit.Init = function () {
        $("#addGroup").click(function(){
            action = "addGroup";
            $("#editGroupDialog").modal("show");
        });

        $('#editGroupDialog').on('hide.bs.modal', function () {
            var $formObj = $("form[name='groupForm']");
                $formObj.data('bootstrapValidator').resetForm();
                $formObj[0].reset();
        });

        $("#serBtn").click(function(){
            $table.bootstrapTable("refresh");
        });

        $("#editGroup").click(function(){
            action = "editGroup";
            var selRows =  $table.bootstrapTable('getSelections');
            var groupId = 0;
            if (selRows.length !== 1) {
                bootbox.alert("<h4 class='caption-subject font-red-sunglo'><i class='glyphicon glyphicon-exclamation-sign'></i> 请选择一个需要编辑的用户！</h4>");
                return;
            }
            for(var k in selRows ) groupId = selRows[k]['id'];

            $("#groupId").val(selRows[0]['id']);

            $.get("/UserManage/get_group",{groupId:groupId},function(ret){
                if (ret.ret === 0) {
                    var groupObj = ret.data;
                    $("#groupName").val(groupObj["group_name"]);
                    $("#phoneNumber").val(groupObj["phone_number"]);
                    $("#editGroupDialog").modal("show");
                } else {
                    noty({
                        text: '<span>'+ ret.msg + '[' + ret.ret + ']' +'</span>',
                        type: 'success',
                        layout: 'topCenter',
                        closeWith: ['hover','click','button']
                    });
                }
            })
        });

        $("#delGroup").click(function() {
            var selRows =  $table.bootstrapTable('getSelections');
            var ids = [];
            if (selRows.length === 0) {
                bootbox.alert("<h4 class='caption-subject font-red-sunglo'><i class='glyphicon glyphicon-exclamation-sign'></i> 请选择需要删除的组！</h4>");
                return;
            }
                
            for(var k in selRows ) ids.push(selRows[k]['id']);

            bootbox.dialog({
                message: "<h4 class='caption-subject font-red-sunglo'><i class='glyphicon glyphicon-exclamation-sign'></i> 是否删除所选组？</h4>",
                buttons:{
                    OK:{
                        label : "确定",
                        className : "btn-info",
                        callback : function() {
                            $.post('/UserManage/del_group',{ids:JSON.stringify(ids)},function(ret){
                                noty({
                                    text: '<span>'+ ret.msg + '[' + ret.ret + ']' +'</span>',
                                    type: 'success',
                                    layout: 'topCenter',
                                    closeWith: ['hover','click','button']
                                });
                                $('#groupLists').bootstrapTable("refresh");
                            });
                        }
                    },
                    Cancel:{
                        label : "取消",
                        className : "btn",
                        callback : function() {
                            
                        }
                    }
                },
                onEscape: true
            });
        });

        $("#addGroupBtn").click(function(e){
            e.preventDefault();
            var validator = $("form[name='groupForm']").data("bootstrapValidator"); 
           
           	validator.validate();
 
            if (validator.isValid()) {
                var params = {};
                if (action === "editGroup") params.id = $("#groupId").val();
                params.action = action;
                params.groupName = $("#groupName").val();
                params.phoneNumber = $("#phoneNumber").val();
                $.post('/UserManage/edit_group',params,function(ret) {
                    $("#editGroupDialog").modal("hide");
                    noty({
                        text: '<span>'+ ret.msg + '[' + ret.ret + ']' +'</span>',
                        type: 'success',
                        layout: 'topCenter',
                        closeWith: ['hover','click','button']
                    });
                    $('#groupLists').bootstrapTable("refresh");
                });
            } 
        });
    };

    return oInit;
};